package com.aifund.common.handler;

import com.aifund.common.enums.CommonEnum;
import com.aifund.common.exception.AiFundException;
import com.aifund.common.result.ResultBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = AiFundException.class)
    @ResponseBody
    public ResultBody bizExceptionHandler(HttpServletRequest req, AiFundException e) {
        logger.error("发生业务异常！原因是：{}","服务端："+ e.getServiceMsg()+"  "+"客户端： "+e.getErrorMsg());
        return ResultBody.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("发生空指针异常！原因是: {}:", e);
        return ResultBody.error(CommonEnum.BODY_NOT_MATCH);
    }


    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultBody exception(MethodArgumentNotValidException e) {
        logger.error("参数校验异常！原因是: {}", e.getFieldError().getDefaultMessage());
        return ResultBody.error(CommonEnum.PARAM_VALID_ERROR.getResultCode(),e.getFieldError().getDefaultMessage());
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResultBody bindException(BindException e) {
        logger.error("校验多个错误！原因是: {}", e.getFieldError().getDefaultMessage());
        return ResultBody.error(CommonEnum.PARAM_VALID_ERROR.getResultCode(),e.getFieldError().getDefaultMessage());
    }

    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("未知异常！原因是: {}", e);
        return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

}



